package com.apestech.framework.util;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
import com.apestech.framework.file.BufferFileRead;
import com.apestech.framework.file.FileFind;
import com.apestech.framework.file.callback.FileCallBackHandler;
import com.apestech.framework.file.callback.ReadBufferFileCallBackHandler;
import com.apestech.framework.file.callback.VarOperCallBack;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 文件,目录相关处理函数集
 * @author hupo
 *
 */
public class FileUtil extends StringUtil {
	
	public static String getFileName(String fileName){
		File f = new File(fileName);
		if(f.exists()){
			String file=f.getName();
			return file;
		}
		return "";
	}

	public static String getFilePath(String fileName){
		File f = new File(fileName);
		return f.getParent();
	}

	public static String getFileNameForSys(String fileName) throws Exception {
		if(fileName==null) return null;
		fileName=fileName.replace("/", File.separator);
		fileName=fileName.replace("\\", File.separator);
		return fileName;
	}

	public static String getClassAbsolutePath(String dName) {
		String absolutePath = File.separator+dName+File.separator;
		String rootPath = new File("").getAbsolutePath();
		File file = new File(rootPath, absolutePath);
		if (file.exists()) {
			return file.getAbsolutePath();
		}
		absolutePath = ".."+File.separator+dName+File.separator;
		file = new File(rootPath, absolutePath);
		if (file.exists()) {
			return file.getAbsolutePath();
		}
		return null;
	}

	public static String getFileAbsolutePath(String filename){
		File file=new File(filename);
		if(file.exists()){
			return file.getAbsolutePath();
		}
		return null;
	}
	
	/**
	 * 判断文件所在目录是否存在,不存在会创建目录
	 * @param fileName String 文件名 String 文件名
	 * @throws IOException
	 */
	public static void createDir(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			if (!file.exists()) {  //&& !file.isDirectory()
				DBUtil.getSys();
				if (fileName.indexOf(File.separator) >= 0) {
					new File(file.getParent()).mkdirs();
				}
				file=null;
			}
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 该方法仅只判断文件或者目录是否合法
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static boolean fileExists(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			boolean flag=file.exists();
			return flag;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	public static boolean isFile(String fileName) throws Exception {
		try {
			if(fileName==null) return false;
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			boolean flag=file.exists();
			if(flag) flag=file.isFile();
			return flag;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}


	/**
	 * 获取文件
	 * @param fileName
	 * @return
	 */
	public static File getFile(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			if (!file.exists()) {  // || !file.isDirectory()
				file=null;
			}
			return file;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static File newFile(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			if (!file.exists()) {
				if (fileName.indexOf(File.separator) >= 0) {
					new File(file.getParent()).mkdirs();
				}
				file.createNewFile();
			}
			return file;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 创建新文件,如果文件路径不存在,将会自动生成路径再创建文件
	 * @param fileName String 文件名 String 文件名
	 * @return
	 * @throws IOException
	 */
	public static boolean createFile(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			if (file.exists()) {
				file=null;
				return true;
			} else {
				if (fileName.indexOf(":") >= 0) {
					new File(file.getParent()).mkdirs();
				}
				file.createNewFile();
				return false;
			}
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 判断文件是否存在
	 * @param fileName String 文件名
	 * @return
	 * @throws IOException
	 */
	public static boolean isFileExist(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			File file = new File(fileName);
			if (file.exists()) {
				file=null;
				return true;
			} else {
				file=null;
				return false;
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 删除指定目录下的全部指定文件
	 * @param path
	 * @param fileName
	 * @throws IOException
	 */
	public void delFile(String path, String fileName) throws Exception{
		try {
			fileName=getFileNameForSys(fileName);
			path=getFileNameForSys(path);
			ArrayList<String> list=getFieldList(path, fileName);
			int len=list.size();
			for(int i=0; i<len; i++){
				deleteFile(list.get(i));
			}
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * @param path String 被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDir(String path) throws Exception {
		try {
			path=getFileNameForSys(path);
            // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			File dirFile = new File(path);
			// 如果dir对应的文件不存在，或者不是一个目录，则退出
			if (!dirFile.exists() || !dirFile.isDirectory()) {
				return false;
			}
			boolean flag = true;
			// 删除文件夹下的所有文件(包括子目录)
			File[] files = dirFile.listFiles();
			for (int i = 0; i < files.length; i++) {
				// 删除子文件
				if (files[i].isFile()) {
					flag = deleteFile(files[i].getAbsolutePath());
					if (!flag)
						break;
				} // 删除子目录
				else {
					flag = deleteDir(files[i].getAbsolutePath());
					if (!flag)
						break;
				}
			}
			if (!flag)
				return false;
			// 删除当前目录
			if (dirFile.delete()) {
				return true;
			} else {
				return false;
			}
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 删除单个文件
	 * @param fileName String 文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			boolean flag = false;
			File file = new File(fileName);  //路径为文件且不为空则进行删除
			if (file.isFile() && file.exists()) {
				file.delete();
				flag = true;
			}
			return flag;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 获取某一目录下所有一层目录名，不包括前缀路径
	 * @param path
	 * @return
	 */
	public static ArrayList<String> getDirFirstDir(String path) throws Exception {
		try {
			path=getFileNameForSys(path);
			ArrayList<String> list = new ArrayList<String>();
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			File file = new File(path);
			File[] files = file.listFiles();
			int len = files.length;
			for (int i = 0; i < len; i++) {
				if (!files[i].isFile()) {
					File dFile = new File(files[i].getName());
					list.add(dFile.getName());
				}
			}
			return list;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 获取某一目录下所有一层文件名，不包括前缀路径
	 * @param path
	 * @return
	 */
	public static ArrayList<String> getDirFirstFile(String path) throws Exception {
		try {
			path=getFileNameForSys(path);
			ArrayList<String> list = new ArrayList<String>();
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			File file = new File(path);
			File[] files = file.listFiles();
			int len = files.length;
			for (int i = 0; i < len; i++) {
				if (files[i].isFile()) {
					File dFile = new File(files[i].getName());
					list.add(dFile.getName());
				}
			}
			return list;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 内部方法，递归方式检索文件信息
	 * @param path
	 * @param callback
	 * @param params
	 * @return
	 * @throws IOException
	 */
	private static Object lookupFile(String path, FileCallBackHandler callback, Object... params) throws Exception {
		try {
			path=getFileNameForSys(path);
			if (!path.endsWith(File.separator)) {
				path = path + File.separator;
			}
			File dirFile = new File(path);
			Object obj = callback.beforeExec(dirFile, params);
			if (obj != null) {
				if (obj.getClass().getName().indexOf("boolean") >= 0) {
					if (!(boolean) obj) {
						return false;
					}
				} else if (obj.getClass().getName().indexOf("File") >= 0) {
					dirFile = (File) obj;
				}
			}
			boolean flag = true;
			File[] files = dirFile.listFiles();
			if(files==null) return null;
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					obj = callback.operFile(files[i]);
					if (obj != null) {
						if (obj.getClass().getName().indexOf("boolean") >= 0) {
							flag = (boolean) obj;
							if (flag) {
								break;
							}
						}
					}
				} else {
					obj = callback.operDir(files[i]);
					File file = files[i];
					if (obj != null) {
						if (obj.getClass().getName().indexOf("boolean") >= 0) {
							flag = (boolean) obj;
							if (flag) {
								break;
							}
						} else if (obj.getClass().getName().indexOf("File") >= 0) {
							file = (File) obj;
						}
					}

					lookupFile(file.getAbsolutePath(), callback, params);
				}
			}
			return callback.afterExec();
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 获取文件列表
	 * @param path
	 * @return
	 * @throws IOException 
	 */
	public static ArrayList<String> getFieldList(String path) throws Exception{
		return getFieldList(path, null);
	}
	
	/**
	 * 获取文件列表
	 * @param path
	 * @param fileName
	 * @return
	 * @throws IOException 
	 */
	public static ArrayList<String> getFieldList(String path, String fileName) throws Exception{
		try {
			if(path==null) return null;
			if(isFile(path)){
				ArrayList<String> list=new ArrayList<String>();
				list.add(path);
				return list;
			}
			fileName=getFileNameForSys(fileName);
			path=getFileNameForSys(path);
			if(path.indexOf(".")>=0 && path.indexOf(File.separator)<0){
				if(fileExists(path)){
					ArrayList<String> flist = new ArrayList<String>();
					flist.add(path);
					return flist;
				}
			}
			@SuppressWarnings("unchecked")
			ArrayList<String> flist = (ArrayList<String>) lookupFile(path, new FileCallBackHandler() {
				ArrayList<String> flist = new ArrayList<String>();
				String ffileName;

				public Object beforeExec(File file, Object... params) {
					ffileName = (String) params[0];
					return flist;
				}

				public Object operFile(File file) throws Exception {
					String fileName = file.getAbsolutePath();
					if (isFileExt(file.getName(), ffileName)) {
						flist.add(fileName);
					}
					return flist;
				}

				public Object operDir(File file) {
					return flist;
				}

				public Object afterExec() {
					return flist;
				}

			}, fileName);
			return flist;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static int getMaxFileOrder(String path) throws Exception{
		return getMaxFileOrder(path, null);
	}
	
	public static int getMaxFileOrder(String path, String fileName) throws Exception{
		try {
			path=getFileNameForSys(path);
			fileName=getFileNameForSys(fileName);
			@SuppressWarnings("unchecked")
			int num = (int) lookupFile(path, new FileCallBackHandler() {
				int num = -1;
				String ffileName;

				public Object beforeExec(File file, Object... params) {
					ffileName = (String) params[0];
					return num;
				}

				public Object operFile(File file) throws Exception {
					String fileName = file.getAbsolutePath();
					if (isFileExt(file.getName(), ffileName)) {
						String sfile = file.getName();
						sfile = leftStr(sfile, sfile.indexOf("."));
						if (!"index".equals(sfile)) {
							int i = Integer.parseInt(sfile);
							if (num < i) {
								num = i;
							}
						}
					}
					return num;
				}

				public Object operDir(File file) {
					return num;
				}

				public Object afterExec() {
					return num;
				}

			}, fileName);
			return num;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static int getMinFileOrder(String path) throws Exception{
		return getMinFileOrder(path, null);
	}
	
	public static int getMinFileOrder(String path, String fileName) throws Exception{
		try {
			path=getFileNameForSys(path);
			fileName=getFileNameForSys(fileName);
			@SuppressWarnings("unchecked")
			int num = (int) lookupFile(path, new FileCallBackHandler() {
				int num = 1000000;
				String ffileName;

				public Object beforeExec(File file, Object... params) {
					ffileName = (String) params[0];
					return num;
				}

				public Object operFile(File file) throws Exception {
					String fileName = file.getAbsolutePath();
					if (isFileExt(file.getName(), ffileName)) {
						String sfile = file.getName();
						sfile = leftStr(sfile, sfile.indexOf("."));
						int i = Integer.parseInt(sfile);
						if (num > i) {
							num = i;
						}
					}
					return num;
				}

				public Object operDir(File file) {
					return num;
				}

				public Object afterExec() {
					return num;
				}

			}, fileName);
			return num;
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 包括目录在内的文件批量改名，不限文件类型，统一按照该规则修改名字
	 * @param file  文件或目录
	 * @param oldStr 要替换子串
	 * @param newStr 新子串
	 * @throws IOException
	 */
	public static void renameFile(String file, String oldStr, String newStr) throws Exception{
		renameFile(file, oldStr, newStr,  null);
	}
	
	public static void renameFile(String file, VarOperCallBack varOperCallBack) throws Exception{
		renameFile(file, null, null, varOperCallBack);
	}

	/**
	 * 包括目录在内的文件批量改名，可指定文件后缀名
	 * @param path 文件路径
	 * @param oldStr 要替换子串
	 * @param newStr 新子串
	 * @throws IOException
	 */
	private static void renameFile(String path, String oldStr, String newStr, VarOperCallBack varOperCallBack) throws Exception{
		try {
			path=getFileNameForSys(path);
			lookupFile(path, new FileCallBackHandler() {
				String oldStr;
				String newStr;
				File rfile;

				public Object beforeExec(File file, Object... params) throws Exception {
					oldStr = (String) params[0];
					newStr = (String) params[1];
					String fileName = file.getAbsolutePath();
					String f=file.getName();
					int pos=f.indexOf(".");
					if(pos>=0) f=f.substring(0, pos);
					if(varOperCallBack!=null) return renameFileName(fileName, f, varOperCallBack.getString(f));
					return renameFileName(fileName, oldStr, newStr);
				}

				public Object operFile(File file) throws Exception {
					String fileName = file.getAbsolutePath();
					String f=file.getName();
					int pos=f.indexOf(".");
					if(pos>=0) f=f.substring(0, pos);
					if(varOperCallBack!=null) renameFileName(fileName, f, varOperCallBack.getString(f));
					else renameFileName(fileName, oldStr, newStr);
					return null;
				}

				public Object operDir(File file) throws Exception {
					String fileName = file.getAbsolutePath();
					String f=file.getName();
					int pos=f.indexOf(".");
					if(pos>=0) f=f.substring(0, pos);
					if(varOperCallBack!=null) rfile=renameFileName(fileName, f, varOperCallBack.getString(f));
					else rfile = renameFileName(fileName, oldStr, newStr);
					return rfile;
				}

				public Object afterExec() {
					return rfile;
				}

			}, oldStr, newStr);
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 是否为符合条件后缀文件名
	 * @param fileName
	 * @return
	 */
	private static boolean isFileExt(String fileName, String ffileName) throws Exception {
		try {
			if (ffileName == null) {
				return true;
			}
			fileName=getFileNameForSys(fileName);
			ffileName=getFileNameForSys(ffileName);
			FileFind file = new FileFind(ffileName);
			boolean flag = file.isMate(fileName);
			file = null;
			return flag;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 开启属性文件
	 * @param fileName String 文件名
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static Properties openPropFile(String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			Properties prop = new Properties(); // 属性集合对象
			FileInputStream fis;
			fis = new FileInputStream(fileName);
			prop.load(fis);
			fis.close();
			return prop;
		} catch (FileNotFoundException e) {
			throw new Exception(e.getMessage());
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 保存属性文件
	 * @param prop
	 * @param fileName String 文件名
	 * @throws IOException
	 */
	public static void saveProgFile(Properties prop, String fileName)
			throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			FileOutputStream fos = new FileOutputStream(fileName);
			prop.store(fos, "Copyright (c) YuanYuanSoftWare");
			fos.close();
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 将字串保存为文本类型文件,后缀名可调
	 * @param text     String 保存文件的字串
	 * @param fileName String 文件名
	 */
	public static void saveTxtFile(String text, String fileName) throws Exception {
		try {
			fileName=getFileNameForSys(fileName);
			FileOutputStream fos = new FileOutputStream(fileName);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			osw.write(text);
			osw.flush();
			osw.close();
			fos.close();
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 将文本类型的内容转换为字串
	 * @param fileName String 文件名
	 * @return
	 */
	public static String readTxtFile(String fileName) throws Exception {
		String text = "";
		try {
			fileName=getFileNameForSys(fileName);
			FileInputStream fis = new FileInputStream(fileName);
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			BufferedReader reader = new BufferedReader(isr);
			String line = reader.readLine();
			while (line != null) {
				text = text + line;
				line = reader.readLine();
			}
			reader.close();
			fis.close();
		} catch (FileNotFoundException e) {
			throw new Exception(e.getMessage());
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		return text;
	}
	
	/**
	 * 文件重命名，入参为字串类型的文件名
	 * @param fileName
	 * @param oldStr
	 * @param newStr
	 * @return
	 * @throws IOException
	 */
	public static File renameFileName(String fileName, String oldStr, String newStr) throws Exception{
		try {
			fileName=getFileNameForSys(fileName);
			if ("".equals(fileName) || fileName == null) {
				return null;
			}
			File file = new File(fileName);
			return renameFileName(file, oldStr, newStr);
		} catch (IOException e) {
			throw new Exception(e.getMessage());
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	/**
	 * 文件重命名，入参为File类型
	 * @param file
	 * @param oldStr
	 * @param newStr
	 * @return
	 * @throws IOException
	 */
	public static File renameFileName(File file, String oldStr, String newStr) throws Exception{
		try {
			if (file == null) {
				return null;
			}
			String fileName = file.getName();
			fileName=getFileNameForSys(fileName);
			fileName = fileName.replace(oldStr, newStr).trim();
			File nfile = new File(file.getParentFile() + "\\" + fileName);
			file.renameTo(nfile);
			return nfile;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static long getStrSize(String text) throws Exception{
		try {
			return text.getBytes().length;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
	
	public static long getFileSize(String fileName) throws Exception{
		try {
			fileName=getFileNameForSys(fileName);
			File f = new File(fileName);
			if (f.exists() && f.isFile()) {
				return f.length();
			} else {
				return 0;
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	public static void copyFileUsingFileStreams(String source, String dest)
			throws Exception {
		InputStream input = null;
		OutputStream output = null;
		try {
			if(fileExists(source)){
				createDir(dest);
				input = new FileInputStream(new File(source));
				output = new FileOutputStream(new File(dest));
				byte[] buf = new byte[1024];
				int bytesRead;
				while ((bytesRead = input.read(buf))!=-1){
					output.write(buf, 0, bytesRead);
				}
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if(input!=null) input.close();
			if(output!=null) output.close();
		}
	}

	public static String getXmlStr(String filename) throws Exception {
		String t= "";
		BufferFileRead read=new BufferFileRead(filename);
		final String[] txt = {""};
		read.getFileText(new ReadBufferFileCallBackHandler(){
			@Override
			public boolean read(String text, int index) throws Exception {
				if(text==null) return true;
				if(text.indexOf("<?xml")<0){
					int pos=text.indexOf("--");
					int ipos=text.indexOf("<!--");
					if(pos>=0 && pos-ipos!=2){
						text=leftStr(text, pos);
					}
					if("".equals(text.trim())) text="";
					txt[0] = txt[0] +text;
				}
				return false;
			}
		}, 0);
		t=txt[0];
		read.close();
		return t;
	}

	public static void copyFile(String source, String desc) throws Exception {
		createDir(desc);
		File sourFile=new File(source);
		File descFile=new File(desc);
		copyFileUsingFileChannels(sourFile, descFile);
	}

	private static void copyFileUsingFileChannels(File source, File dest) throws Exception {
		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try {
			inputChannel = new FileInputStream(source).getChannel();
			outputChannel = new FileOutputStream(dest).getChannel();
			outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		} finally {
			inputChannel.close();
			outputChannel.close();
		}
	}

	public static String codeString(String fileName) throws Exception {
		BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
		int p = (bin.read() << 8) + bin.read();
		bin.close();
		String code = null;
		switch (p) {
			case 15423:
				code = "UTF-8";
				break;
			case 20562:
				code = "UTF-8";
				break;
			case 58552:
				code = "UTF-8";
				break;
			case 31522:
				code = "UTF-8";
				break;
			case 0xefbb:
				code = "UTF-8";
				break;
			case 0xfffe:
				code = "Unicode";
				break;
			case 0xfeff:
				code = "UTF-16BE";
				break;
			default:
				code = "GBK";
		}
		return code;
	}

	public static void toZip(ArrayList<File> fileList, String fname) throws Exception{
		if(null != fileList && !fileList.isEmpty()){
			byte[] buf = new byte[1024];
			String fi = fname;
			FileOutputStream os = new FileOutputStream(fi);
			ZipOutputStream zipOut = new ZipOutputStream(os);
			zipOut.setEncoding("utf-8");
			for(File file : fileList){
				FileInputStream in = new FileInputStream(file);
				zipOut.putNextEntry(new ZipEntry(file.getName()));
				int len;
				while((len = in.read(buf)) > 0){
					zipOut.write(buf, 0, len);
				}
				zipOut.closeEntry();
				in.close();
				file.delete();//清除临时文档
			}
			zipOut.close();
		}
	}

	public static String unZip(String filename) throws Exception {
		String path=getFileAbsolutePath(filename);
		if(path!=null){
			path=path+File.separator+"tempzip";
			unZip(filename, path);
			return path;
		}
		return null;
	}

	public static void unZip(String filename, String outDir) throws Exception {
		File zipFile=new File(filename);
		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (isMakDir) {
				System.out.println("创建压缩目录成功");
			}
		}
		ZipFile zip = new ZipFile(zipFile,"GBK");
		for (Enumeration enumeration = zip.getEntries(); enumeration.hasMoreElements(); ) {
			String odir=outDir;
			ZipEntry entry = (ZipEntry) enumeration.nextElement();
			String zipEntryName = entry.getName();
			zipEntryName=getFileNameForSys(zipEntryName);
			InputStream in = zip.getInputStream(entry);
			//if (entry.isDirectory()) {      //处理压缩文件包含文件夹的情况
			int pos=zipEntryName.lastIndexOf(File.separator);
			if(pos>0){
				File fileDir = new File(outDir + zipEntryName.substring(0, pos));
				fileDir.mkdir();
				if(zipEntryName.indexOf(".")<0){
					continue;
				}
			} else {
				String sub=filename.substring(filename.lastIndexOf(File.separator)+1, filename.lastIndexOf("."));
				File fileDir = new File(outDir + sub);
				fileDir.mkdir();
				odir=outDir+sub;
			}
			File file = new File(odir, zipEntryName);
			file.createNewFile();
			OutputStream out = new FileOutputStream(file);
			byte[] buff = new byte[1024];
			int len;
			while ((len = in.read(buff)) > 0) {
				out.write(buff, 0, len);
			}
			in.close();
			out.close();
		}
	}

	public static String unRar(String filename) throws Exception {
		String path=getFileAbsolutePath(filename);
		if(path!=null){
			path=path+File.separator+"temprar";
			unRar(filename, path);
			return path;
		}
		return null;
	}

	public static void unRar(String filename, String outDir) throws Exception {
		File rarFile=new File(filename);
		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (isMakDir) {
				System.out.println("创建压缩目录成功");
			}
		}
		Archive archive = new Archive(new FileInputStream(rarFile));
		FileHeader fileHeader = archive.nextFileHeader();
		while (fileHeader != null) {
			if (fileHeader.isDirectory()) {
				fileHeader = archive.nextFileHeader();
				continue;
			}
			File out = new File(outDir + fileHeader.getFileNameString());
			if (!out.exists()) {
				if (!out.getParentFile().exists()) {
					out.getParentFile().mkdirs();
				}
				out.createNewFile();
			}
			FileOutputStream os = new FileOutputStream(out);
			archive.extractFile(fileHeader, os);

			os.close();

			fileHeader = archive.nextFileHeader();
		}
		archive.close();
	}

	public static byte[] fileToByte(String filename) throws Exception {
		File file = new File(filename);
		byte[] byt = new byte[(int) file.length()];
		FileInputStream fis = new FileInputStream(file);
		fis.read(byt); //read file into bytes[]
		fis.close();
		return byt;
	}

	public static void byteToFile(String filename, byte[] byt) throws Exception {
		FileOutputStream fos = new FileOutputStream(filename);
		fos.write(byt);
		fos.close();
	}

}
